package ch.subgate.spritestudio;

import java.util.ArrayList;

import ch.subgate.spritestudio.tools.DataManager;
import ch.subgate.spritestudio.tools.DialogHelper;
import ch.subgate.spritestudio.tools.ImageProcessing;
import ch.subgate.spritestudio.tools.OnColorChangedListener;
import ch.subgate.spritestudio.types.ColorAdapter;
import ch.subgate.spritestudio.types.Palette;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Toast;

public class PaletteActivity extends Activity implements
OnClickListener,
OnItemClickListener,
OnItemSelectedListener,
OnColorChangedListener {
	
	private int mEditPosition;
	
	private int mCurrentColor;
	
	private int mCurrentPalette;
	
	private ArrayList<Palette> mPalettes;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.palette_layout);
		
		mEditPosition = 0;
		
		Intent intent = this.getIntent();
		
		if (intent != null) {
			mCurrentColor = intent.getIntExtra("currentcolor", 0);
		}
		
		// Make sure the required directories exist
		DataManager.mkdirs();
		
		// Loading palettes from sdcard
		mPalettes = new ArrayList<Palette>();
		Palette.loadPalettes(mPalettes);
		
		// Fill spinner with loaded palettes and set item click listener
		Spinner spinner = (Spinner)findViewById(R.id.palettespinner);
		ArrayAdapter<Palette> adapter = new ArrayAdapter<Palette>(
				this.getApplicationContext(),
				android.R.layout.simple_spinner_item,
				mPalettes);
		adapter.setDropDownViewResource(
				android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(this);
		
		// Fill gridview with colors from current palette and set item click listener
		GridView gridView = (GridView)findViewById(R.id.palettegrid);
		ColorAdapter gridColors;
		
		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		if (mPalettes.size() > 0) {
			gridColors = new ColorAdapter(
					this.getApplicationContext(),
					mPalettes.get(mCurrentPalette).getColors(),
					outMetrics.densityDpi);
		}
		else {
			gridColors = new ColorAdapter(
					this.getApplicationContext(),
					null,
					outMetrics.densityDpi);
		}
		gridView.setAdapter(gridColors);
		gridView.setOnItemClickListener(this);
		registerForContextMenu(gridView);
		
		// Set OnClickListeners on the buttons
		findViewById(R.id.palettenew).setOnClickListener(this);
		findViewById(R.id.paletteaddcolor).setOnClickListener(this);
		findViewById(R.id.palettecurrentcolor).setOnClickListener(this);
		findViewById(R.id.palettebuvr).setOnClickListener(this);
		findViewById(R.id.palettebdvr).setOnClickListener(this);
		findViewById(R.id.palettebumr).setOnClickListener(this);
		findViewById(R.id.palettebdmr).setOnClickListener(this);
		
		// Set image views background to current color
		ImageButton button = (ImageButton)findViewById(R.id.palettecurrentcolor);
		button.setBackgroundColor(mCurrentColor);
	}
	
	@Override
	public void onDestroy() {
		if (mPalettes != null) {
			mPalettes.clear();
			mPalettes = null;
		}
		super.onDestroy();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info) {
		super.onCreateContextMenu(menu, v, info);
		
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.palettecontext_menu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		
		GridView grid = (GridView)findViewById(R.id.palettegrid);
		ColorAdapter adapter = (ColorAdapter)grid.getAdapter();
		
		switch (item.getItemId()) {
		case R.id.pcedit:
			mEditPosition = info.position;
			DialogHelper.showColorPickerDialog(
					this,
					this,
					mPalettes.get(mCurrentPalette).getColors().get(info.position));
			break;
		case R.id.pccurrent:
			mPalettes.get(mCurrentPalette).getColors().set(
					info.position,
					Integer.valueOf(mCurrentColor));
			adapter.notifyDataSetChanged();
			Palette.savePalette(mPalettes.get(mCurrentPalette));
			break;
		case R.id.pcdelete:
			mPalettes.get(mCurrentPalette).getColors().remove(info.position);
			adapter.notifyDataSetChanged();
			Palette.savePalette(mPalettes.get(mCurrentPalette));
			break;
		}
		return true;
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// Set new color
		mCurrentColor = mPalettes.get(mCurrentPalette).getColors().get(position);
		
		// Update the current color view
		ImageButton button = (ImageButton)findViewById(R.id.palettecurrentcolor);
		button.setBackgroundColor(mCurrentColor);
	}

	@Override
	public void onClick(View v) {
		SeekBar bseeker = (SeekBar)findViewById(R.id.palettebseek);
		ImageButton button = (ImageButton)findViewById(R.id.palettecurrentcolor);
		int bseekerProgress = bseeker.getProgress();
		
		switch (v.getId()) {
		case R.id.palettenew:
			EditText et = (EditText)findViewById(R.id.palettename);
			if (et.getText().length() > 0) {
				mPalettes.add(
						new Palette(
								et.getText().toString(),
								new ArrayList<Integer>()));
				Spinner spinner = (Spinner)findViewById(R.id.palettespinner);
				ArrayAdapter<?> adapter = (ArrayAdapter<?>)spinner.getAdapter();
				adapter.notifyDataSetChanged();
				mCurrentPalette = mPalettes.size() - 1;
				GridView grid = (GridView)findViewById(R.id.palettegrid);
				ColorAdapter colorAdapter = (ColorAdapter)grid.getAdapter();
				colorAdapter.setColors(mPalettes.get(mCurrentPalette).getColors());
				colorAdapter.notifyDataSetChanged();
				Palette.savePalette(mPalettes.get(mCurrentPalette));
			}
			else {
				Toast.makeText(
						getApplicationContext(),
						"Enter a palette name first.",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.paletteaddcolor:
			if (mPalettes != null) {
				if (!mPalettes.isEmpty()) {
					if (mPalettes.get(mCurrentPalette).getColors().size() < 255) {
						mPalettes.get(mCurrentPalette).addColor(mCurrentColor);
						GridView gridView = (GridView)findViewById(R.id.palettegrid);
						ColorAdapter adapter = (ColorAdapter)gridView.getAdapter();
						adapter.notifyDataSetChanged();
						Palette.savePalette(mPalettes.get(mCurrentPalette));
					}
					else {
						Toast.makeText(
								getApplicationContext(),
								"Maximum color number reached.",
								Toast.LENGTH_SHORT).show();
					}
				}
			}
			break;
		case R.id.palettecurrentcolor:
			for (Palette palette : mPalettes) {
				Palette.savePalette(palette);
			}
			Intent intent = new Intent();
			intent.putExtra("resultcolor", mCurrentColor);
			this.setResult(RESULT_OK, intent);
			finish();
			break;
		case R.id.palettebuvr:
			mCurrentColor = ImageProcessing.changeBrightness(
					mCurrentColor,
					bseekerProgress * 10,
					true);
			button.setBackgroundColor(mCurrentColor);
			break;
		case R.id.palettebdvr:
			mCurrentColor = ImageProcessing.changeBrightness(
					mCurrentColor,
					bseekerProgress * 10 * -1,
					true);
			button.setBackgroundColor(mCurrentColor);
			break;
		case R.id.palettebumr:
			mCurrentColor = ImageProcessing.changeBrightness(
					mCurrentColor,
					bseekerProgress * 10,
					false);
			button.setBackgroundColor(mCurrentColor);
			break;
		case R.id.palettebdmr:
			mCurrentColor = ImageProcessing.changeBrightness(
					mCurrentColor,
					bseekerProgress * 10 * -1,
					false);
			button.setBackgroundColor(mCurrentColor);
			break;
		}
	}

	@Override
	public void onColorChanged(int color) {
		mPalettes.get(mCurrentPalette).getColors().set(mEditPosition, Integer.valueOf(color));
		GridView grid = (GridView)findViewById(R.id.palettegrid);
		ColorAdapter adapter = (ColorAdapter)grid.getAdapter();
		adapter.notifyDataSetChanged();
		Palette.savePalette(mPalettes.get(mCurrentPalette));
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		mCurrentPalette = position;
		GridView grid = (GridView)findViewById(R.id.palettegrid);
		ColorAdapter adapter = (ColorAdapter)grid.getAdapter();
		adapter.setColors(mPalettes.get(mCurrentPalette).getColors());
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
	}
}
